package org.real.guetshop.controller.admin;

import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.real.guetshop.pojo.dto.ProductDTO;
import org.real.guetshop.pojo.dto.ProductQueryDTO;
import org.real.guetshop.pojo.entity.Category;
import org.real.guetshop.pojo.entity.Product;
import org.real.guetshop.result.PageResult;
import org.real.guetshop.result.Result;
import org.real.guetshop.service.ProductService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@RestController("adminProductController")
@RequestMapping("/admin/product")
public class ProductController {

    @Resource
    private ProductService productService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 清除缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    /**
     * 新增商品
     * @param productDTO
     * @return
     */
    @Operation(summary = "商品新增")
    @CacheEvict(cacheNames = "product",key = "'category_'+#productDTO.categoryId")
    @PostMapping("/add")
    public Result add(@RequestBody ProductDTO productDTO) {
        log.info("新增商品：{}", productDTO);

        productService.addNewProduct(productDTO);

        //清除缓存数据
//        String key = "product_" + productDTO.getCategoryId();
//        cleanCache(key);
        //在清除没有分类的全部商品
        cleanCache("products");

        return Result.success();
    }

    /**
     * 修改商品
     * @param productDTO
     * @return
     */
    @CacheEvict(cacheNames = "product",key = "'category_'+#productDTO.categoryId")
    @Operation(summary = "商品修改")
    @PutMapping("/update")
    public Result update(@RequestBody ProductDTO productDTO) {
        log.info("开始对商品进行修改{}", productDTO);
        productService.update(productDTO);

        //将所有的分类商品缓存数据清理掉，所有以product_开头的key
//        cleanCache("product_*");
        //在清除没有分类的全部商品
        cleanCache("products");

        return Result.success();
    }

    /**
     * 商品批量删除
     */
    @Operation(summary = "商品批量删除")
    @DeleteMapping("/delete")
    public Result delete(@RequestParam(value = "ids") List<Integer> ids) {
        log.info("开始对商品进行批量删除：{}",ids);
        productService.deleteBatch(ids);

        //将所有的商品缓存数据清理掉，所有以product_开头的key
        cleanCache("product::category_*");

        return Result.success();
    }

    /**
     * 商品分页查询
     * @param productQueryDTO
     * @return
     */
    @Operation(summary = "商品分页查询")
    @PostMapping("/page")
    public  Result<PageResult> page(@RequestBody ProductQueryDTO productQueryDTO) {
        log.info("商品分页查询：{}",productQueryDTO);
        PageResult pageResult = productService.pageQuery(productQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 根据分类id查询商品
     * @param categoryId
     * @return
     */
    @Operation(summary = "根据分类id查询商品")
    @GetMapping("/category/{categoryId}")
    @Cacheable(value = "product",key = "'category_' + #categoryId")
    public Result<List<Product>> getByCategoryId(@PathVariable(value = "categoryId") Integer categoryId) {
        log.info("根据分类id查询商品：{}",categoryId);
        List<Product> list =productService.queryByCategoryId(categoryId);
        return Result.success(list);
    }

    /**
     * 商品售卖状态修改
     * @param status
     * @param id
     * @return
     */
    @Operation(summary = "商品售卖状态修改")
    @PutMapping("/status")
    public Result editStatus(@RequestParam(value = "status") Integer status, @RequestParam(value = "id") Integer id) {
        log.info("开始修改商品售卖状态：{}",id);
        productService.editStatus(id,status);

        //将所有的商品缓存数据清理掉，所有以product_开头的key
        cleanCache("product::category_*");

        return Result.success();
    }

    /**
     * 根据商店id查询商品
     * @param storeId
     * @return
     */
    @Operation(summary = "根据商店id查询商品")
    @GetMapping("/store/{storeId}")
    public Result<List<Product>> getByStoreId(@PathVariable(value = "storeId") Integer storeId) {
        log.info("根据商店id查询商品：{}",storeId);
        List<Product> list =productService.queryByStoreId(storeId);
        return Result.success(list);
    }

    /**
     * 获取分类列表
     * @return
     */
    @Operation(summary = "获取分类列表")
    @GetMapping("/category")
    public Result<List<Category>> getCategories(){
        return Result.success(productService.getCategory());
    }


    /**
     * 定时清理redis
     */
    @Scheduled(fixedRate =  60000) // 每天执行一次
    @CacheEvict(value = "product::category_*", allEntries = true)
    public void clearProductCache() {
        log.info("开始清除商品缓存");
        // 这里可以添加日志记录等操作
    }
}
